import React, { Component } from 'react';
import { StyleSheet, Text, View, Image, ScrollView, PixelRatio, TouchableOpacity } from "react-native";
import { NavigationEvents } from 'react-navigation';
import { GLOBAL } from '../../config/global';
import StorageHelper from '../../utils/storageHelper';
import { STORAGE_CONSTANT } from '../../config/storage';
import { style } from '../../theme/style';
import { API, API_GENERATE } from '../../config/api';
import HTTP from '../../utils/http';
import { Loading } from '../../component/page-status/Pageloading';
import { ToolData } from './_common/toolData';
import Permission from '../../utils/permission';
import { CommonDialog } from '../../components/common/Dialog';
import { NewAccount } from '../../components/common/newAccount';
import { SlideSelect } from '../../components/common/slideSelect';

const scale = GLOBAL.SCALE;
const addIcon = require('../../imgs/customer/company-add.jpg');
const claimIcon = require('../../imgs/customer/renling.jpg');

export class CrMtManage extends Component {
	static navigationOptions = {
		header: null
	}

	constructor(props) {
		super(props);
		this.state = {
			topList: null,
			loading: true,
			total: 0,  // 客户总数
			newly: 0,  //最近一个星期新增客户数
			modalVisible: false,
			alertShow: false,
			options: [],
			choice: {}
		}
		this.toolData = [];
	}

	async	componentWillMount () {
		await this.getSorage();
		await this._getToolData();
		await this._init();
	}

	componentWillUnmount () {
	}

	//获取业务组织
	async getSorage () {
		const userInfoJson = await StorageHelper.get(STORAGE_CONSTANT.USER_INFO_KEY);
		const userInfo = JSON.parse(userInfoJson);
		this.setState({
			options: userInfo.corpInfoTOs || [],
			choice: this.state.choice.corpId ? this.state.choice : userInfo.corpInfoTOs[0]
		})
	}

	//初始函数
	_init = async () => {
		// 顶部代办列表数据
		let total = 0;
		let newly = 0;
		let resData = await HTTP.GET(API_GENERATE(API.CUSTOMER_MANAGE), { corpId: this.state.choice.corpId });
		if (resData) {
			resData.forEach((item) => {
				if (item.cntCode == "total") {
					total = item.cnt;
				}
				if (item.cntCode == "newly") {
					newly = item.cnt;
				}
			})
			this.setState({
				topList: resData,
				total,
				newly,
				loading: false
			})
		} else {
			this.setState({
				loading: false,
				emptyText: '暂无代办统计'
			})
		}

	}

	// 企业工具
	_getToolData = () => {
		this.toolData.push(ToolData['1']);
		this.toolData.push(ToolData['2']);
		this.toolData.push(ToolData['3']);
		this.toolData.push(ToolData['4']);
		this.toolData.push(ToolData['5']);
		this.toolData.push(ToolData['6']);
		console.log('Permission.permissions', Permission.permissions)
		Permission.permissions.forEach((item) => {
			if (ToolData[item]) {
				this.toolData.push(ToolData[item]);
			}
		})
	}

	_renderToastWrap = () => {
		return (
			<View>
				<View style={styles.textRow}>
					<Text style={styles.textRowText}>1. 当前拥有客户数：</Text>
					<Text style={[styles.textRowText, styles.textRowTextP]}>当前登录人名下拥有的企业数</Text>
				</View>
				<View style={styles.textRow}>
					<Text style={styles.textRowText}>2. 最近一周新增：</Text>
					<Text style={[styles.textRowText, styles.textRowTextP]}>当前登录人名下近7天（当天往前合计7天）新增企业数</Text>
				</View>
				<View style={styles.textRow}>
					<Text style={styles.textRowText}>3. 客户资质到期：</Text>
					<Text style={[styles.textRowText, styles.textRowTextP]}>当前查询企业范围数据内，企业资质“已到期、30天内即将到期</Text>
					<Text style={[styles.textRowText, styles.textRowTextP]}>{`(统计公式：到期日期-当前日期<=30天)`}</Text>
				</View>

				<View style={styles.textRow}>
					<Text style={styles.textRowText}>4. 授信账户到期</Text>
					<Text style={[styles.textRowText, styles.textRowTextP]}>当前查询企业数据内，企业授信账户（赊销/预付算1个）</Text>
					<Text style={[styles.textRowText, styles.textRowTextP]}>{`已到期、30天即将到期(统计公式：到期日期-当前日期<=30天)`}</Text>
				</View>
				<View style={styles.textRow}>
					<Text style={styles.textRowText}>5.企业已锁定：</Text>
					<Text style={[styles.textRowText, styles.textRowTextP]}>当前登录人名下关联的企业（停用+冻结）数</Text>
				</View>
				<View style={styles.textRow}>
					<Text style={styles.textRowText}>6. 7天内将流失：</Text>
					<Text style={[styles.textRowText, styles.textRowTextP]}>{`当前登录人名下即将流失的企业-产品（公式：到期日期-当前日期<=7天），已经流失不统计`}</Text>
				</View>
				<View style={styles.textRow}>
					<Text style={styles.textRowText}>7.超15天未跟进：</Text>
					<Text style={[styles.textRowText, styles.textRowTextP]}>{`当前登录人名下企业，认领后未进行维护（统计公式：当前日期-维护日期 >=15天`}</Text>
				</View>
			</View>
		)
	}

	//跳转
	_goPage = (code) => {
		if (code == 'qualification') {
			this.props.navigation.navigate('EnterpriseWarning', { tabIndex: 0, choice: this.state.choice });
		} else if (code == 'credit') {
			this.props.navigation.navigate('EnterpriseWarning', { tabIndex: 1, choice: this.state.choice });
		} else if (code == 'locked') {
			this.props.navigation.navigate('CustomerIndexPage', { isLock: 1, choice: this.state.choice });
		} else if (code == 'LOSS') {
			this.props.navigation.navigate('CustomerLossPage', { isLock: true, choice: this.state.choice });
		} else if (code == 'FLOWAWAY') {
			this.props.navigation.navigate('CustomerIndexPage', { maintainFlag: 1, choice: this.state.choice });
		}
	}


	render () {
		let { topList, total, newly, loading, emptyText, modalVisible, alertShow, choice, options } = this.state;
		return (
			<View style={styles.container}>
				<NavigationEvents
					onWillFocus={async ({ action }) => {
						await this.getSorage();
						await this._init();
					}}
				/>
				<View style={[styles.headBox, styles.paddingStyle]}>
					<View style={styles.headTileBox}>
						<Text style={styles.headTitle}>客户管理</Text>
						<View style={{ flexDirection: 'row', alignItems: 'center', justifyContent: 'center', marginLeft: 17 }}>
							<TouchableOpacity style={{ marginRight: 12 * scale }} activeOpacity={0.8}
								onPress={() => {
									this.props.navigation.navigate('EnterpriseCreateBaseInfo', {
										createNew: true,
										choice
									});
								}}>
								<Image source={addIcon} style={{ width: 25, height: 25 }} />
							</TouchableOpacity>
						</View>

					</View>
					{options.length > 1 ?
						<View style={styles.accountSelect}>
							<NewAccount fn={(val) => { this.setState({ alertShow: val }) }} choice={choice.corpName || ''} />
						</View> : null}
					<View style={styles.float}>
						<Text style={styles.headContain}>当前拥有客户数：{total}家，近一周新增：{newly}家</Text>
						<TouchableOpacity onPress={() => { this.setState({ modalVisible: true }) }}>
							<Image style={styles.tipText} source={require('../../imgs/global/query.png')} />
						</TouchableOpacity>
					</View>
				</View>
				<View style={[styles.warningBox, styles.marginStyle]}>
					{
						!loading && topList && topList.map((item, index) => {
							if (item.cntCode == "newly" || item.cntCode == "total") { // 排除所有企业数,和最近一周新增企业数
								return null;
							} else {
								return (
									<TouchableOpacity onPress={() => { this._goPage(item.cntCode) }} style={styles.warningItem} key={index}>
										<Text style={styles.warningNum}>{item.cnt}</Text>
										<Text style={styles.warningText}>{item.cntName || '-'}</Text>
									</TouchableOpacity>
								)
							}
						})
					}
					{loading && <Loading bgShow={true} />}
					{!topList && <Text style={styles.emptyText}>{emptyText}</Text>}
				</View>
				<ScrollView>
					<View style={styles.body}>
						<View style={[styles.toolsBox, styles.marginStyle]}>
							<View style={styles.toolsTitleBox}>
								<Text style={styles.toolsTitle}>我的工具</Text>
							</View>
							<View style={[styles.toolsRow]}>
								{
									this.toolData.length ? this.toolData.map((item, index) => {
										item.parames = item.parames || {};
										item.parames.choice = choice;
										return (<TouchableOpacity onPress={() => { this.props.navigation.navigate(item.pageUrl, item.parames || null) }} style={styles.toolsItem} key={index}>
											<Image style={styles.imgStyle} source={item.icon} />
											<Text style={styles.warningText}>{item.cntName}</Text>
										</TouchableOpacity>)
									}) : null
								}
							</View>
						</View>
					</View>
				</ScrollView>

				<CommonDialog modalVisible={modalVisible} title={'提示'} renderCustom={this._renderToastWrap} onClosePress={() => { this.setState({ modalVisible: false }) }} />
				{options.length ? <SlideSelect alertShow={alertShow} options={options}
					select={(val) => {
						console.log('val', choice);
						this.setState({ choice: val || options[0], alertShow: false }, () => {
							this._init();
						})
					}}
					unselect={() => {
						this.setState({ alertShow: false })
					}} /> : null}
			</View >
		)
	}
}


const styles = StyleSheet.create({
	container: {
		flex: 1,
		backgroundColor: style.color.bgGray
	},
	headBox: {
		height: 185 * scale,
		backgroundColor: style.color.themeColor
	},
	paddingStyle: {
		paddingLeft: 15 * scale,
		paddingRight: 15 * scale
	},
	marginStyle: {
		marginLeft: 15 * scale,
		marginRight: 15 * scale
	},
	headTitle: {
		fontSize: 20 * scale,
		color: style.color.white,
	},
	headTileBox: {
		marginTop: 40 * scale,
		marginBottom: 5 * scale,
		flexDirection: 'row',
		justifyContent: 'space-between'
	},
	headContain: {
		fontSize: 12 * scale,
		color: style.color.white,
	},
	body: {
		flex: 1,
		paddingTop: 10 * scale,
		paddingBottom: 10 * scale
	},
	warningBox: {
		paddingTop: 15 * scale,
		paddingBottom: 15 * scale,
		backgroundColor: style.color.white,
		borderRadius: 10 * scale,
		position: 'relative',
		top: -40 * scale,
		flexDirection: 'row',
		flexWrap: 'wrap',
		minHeight: 80 * scale
	},
	warningItem: {
		width: '33%',
		alignItems: 'center',
		marginBottom: 20 * scale
	},
	warningNum: {
		color: style.color.themeColor,
		fontSize: 18 * scale,
	},
	warningText: {
		color: style.color.font1,
		fontSize: 13 * scale,
		paddingTop: 10 * scale
	},
	toolsRow: {
		flexDirection: 'row',
		flexWrap: 'wrap',
	},
	toolsItem: {
		width: '25%',
		alignItems: 'center',
		paddingTop: 20 * scale
	},
	toolsTitle: {
		fontSize: 18 * scale,
		textAlign: 'center'
	},
	toolsTitleBox: {
		width: '100%',
		borderBottomWidth: 2 * scale,
		borderStyle: 'solid',
		borderColor: '#efefef',
		paddingTop: 20 * scale,
		paddingBottom: 20 * scale,
	},
	toolsBox: {
		backgroundColor: style.color.white,
		borderRadius: 10 * scale,
		paddingBottom: 20 * scale,
		position: 'relative',
		top: -20 * scale,
		minHeight: 250 * scale
	},
	imgStyle: {
		width: 40 * scale,
		height: 40 * scale,
	},
	emptyText: {
		fontSize: 14 * scale,
		textAlign: 'center',
		flex: 1,
		paddingTop: 15 * scale
	},
	float: {
		width: '100%',
		flexDirection: 'row',
		justifyContent: 'space-between',
		alignItems: 'center',
		paddingTop: 5 * scale
	},
	tipText: {
		height: 15 * scale,
		width: 15 * scale,
		tintColor: style.color.white
	},
	textRow: {
		marginBottom: 20 * scale
	},
	textRowText: {
		fontSize: 13 * scale,
		lineHeight: 16 * scale
	},
	textRowTextP: {
		paddingLeft: 13 * scale
	},
	accountSelect: {
		flexDirection: 'row',
		alignItems: 'center',
		justifyContent: 'flex-start',
		marginBottom: 12 * scale
	}
})